package com.lcj.util;

import cn.hutool.core.lang.UUID;
import org.slf4j.MDC;

import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author: liuchangjun
 * @since: 2024/1/3 10:27
 */
public class ThreadMdcUtils {

    private ThreadMdcUtils(){}
    public static Runnable wrapAsync(Runnable task, Map<String, String> context) {
        return () -> {
            if (Objects.isNull(context)) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            if (Objects.isNull(MDC.get(Constants.TRACE_ID))) {
                MDC.put(Constants.TRACE_ID, UUID.randomUUID().toString());
            }
            try {
                task.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
